/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-24 10:53:10
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-26 01:23:24
 * @FilePath: \vue3_nuxt_demo\server\api\note\all.get.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import Joi from 'joi';
import { responseJson } from '@/server/utils/helper';
import { getDB } from '@/server/utils/db';

export default defineEventHandler(
  async (event)=>{

    // 获取请求参数
    const query = await getQuery(event);

    // 数据校验
    const schema = Joi.object({
      pageNo: Joi.number().min(1).required(),
      pageSize: Joi.number().min(10).required()
    });

    // 校验请求体
    try {
      const value = await schema.validateAsync(query);
    }
    catch (error) {
      return responseJson(400,  {
        success: false,
        msg: '参数错误',
        error: error
      });
    }

    // 数据库交互
    const { find, close } = getDB();

    // 查询
    const con = find();

    try {

      const {pageNo = 1, pageSize = 10} = query as any;

      // 限制条数
      const limit = pageSize;

      // 开始位置
      const offset = (pageNo - 1) * pageSize;

      //查询全部文章
      const [rows] = await con.query(
        'SELECT * FROM `notes` LIMIT ? OFFSET ?',
        [Number(limit), offset]
      );

      return  responseJson(200,{
        success: false,
        msg: '获取成功',
        data: rows
      });
    }
    catch (error){

      setResponseStatus(event,500);
      return responseJson(500,{
        success: false,
        msg: '服务器错误',
        error: error
      });
    }
    finally {
      // 释放连接
      close();
    }
})